import {
  Avatar, ConfigProvider, Dropdown, Icon, Layout, Menu, Spin,
} from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import PropTypes from 'prop-types';
import React from 'react';
import request from 'umi-request';

import router from 'umi/router';
import Link from 'umi/link';
import UserContext from '../components/common/UserContext';
import styles from './index.css';
import { updateProjectList } from '../components/storage/ProjectStorage';
import { updateProvinceList } from '../components/storage/ProvinceStorage';

const {
  Header, Content, Footer, Sider,
} = Layout;

export default class BasicLayout extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentMenu: '/',
      currentUser: {},
      showOverlay: true,
    };
    this.linkTo = this.linkTo.bind(this);
    this.logout = this.logout.bind(this);
  }

  componentDidMount() {
    const { location, history } = this.props;

    // 设置一个拦截器来检查未授权的响应
    request.interceptors.response.use((response) => {
      const whiteList = ['/test', '/login']
      if (!whiteList.includes(history.location.pathname)) {
        if (response.status === 401) {
          history.push('/login');
        }
      }
      return response;
    });

    // 1. 进入判断是否登录，如果 pathname 不是 "/login"，页面是 loading 状态，如果没有登录，就跳转到 "/login"
    // 检查当前路径是否不是 '/login'
    if (location.pathname !== '/login') {
      // 发起请求获取当前用户
      request.get('/api/user/current').then((response) => {
        if (response.object) {
          this.setState({ showOverlay: false, currentUser: response.object });
        } else {
          router.push('/login');
        }
      }).catch((error) => {
        global.console.log(error.response);
      });
    }
    // 设置当前菜单状态为当前路径
    this.setState({ currentMenu: location.pathname });

    // 2. 一般首页不是 "/"，需要重定向一下，例如重定向到 "/data/overview", 在此处写明
    // 如果当前路径是 '/'，则重定向到 '/index'
    if (location.pathname === '/') {
      const defaultIndexPath = '/index';
      router.push(defaultIndexPath);
      this.setState({ currentMenu: defaultIndexPath });
    }

    // TODO
    // 发起请求获取项目列表
    updateProjectList();
    updateProvinceList();
  }

  linkTo(item) {
    if (item.key.indexOf('http:') > -1) {
      global.window.location.href = item.key;
    } else {
      router.push(item.key);
      this.setState({ currentMenu: item.key });
    }
  }

  logout() {
    const { history } = this.props;
    request.get('/api/user/logout').then(() => {
      history.push('/login');
    }).catch((error) => {
      global.console.log(error.response);
    });
  }

  render() {
    const dropdown = (
      <Menu>
        <Menu.Item style={{ display: 'flex', alignItems: 'center' }}>
          <Icon type="setting" />
          <Link to="/user/set-password">设置密码</Link>
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item onClick={this.logout}>
          <Icon type="logout" />
          注销
        </Menu.Item>
      </Menu>
    );

    const {
      currentMenu, currentUser, showOverlay,
    } = this.state;
    const { children, location } = this.props;

    if (location.pathname === '/login') {
      return <>{children}</>;
    }

    const getMenu = () => {
      return (
        <Menu theme="dark" mode="inline" onClick={this.linkTo} selectedKeys={[currentMenu]}>
          <Menu.Item key="/index">
            <Icon type="home" />
            <span className="nav-text">首页</span>
          </Menu.Item>
          <Menu.Item key="/test">
            <Icon type="deployment-unit" />
            <span className="nav-text">测试</span>
          </Menu.Item>
          <Menu.Item key="/users">
            <Icon type="user" />
            <span className="nav-text">用户管理</span>
          </Menu.Item>
        </Menu>
      )
    };

    return (
      <UserContext.Provider value={currentUser}>
        <ConfigProvider locale={zhCN}>
          {showOverlay ? (
            <div className={styles.overlay}>
              <Spin size="large" />
            </div>
          ) : (
            <Layout>
              <Layout>
                <Sider className={styles.sider}>
                  <a href="/">
                    <div className={styles.logo} />
                  </a>
                  {getMenu()}
                </Sider>
                <Layout style={{ marginLeft: 200 }}>
                  <Header style={{ background: '#fff', padding: 0 }}>
                    <div style={{ height: 64, float: 'right' }}>
                      <Dropdown overlay={dropdown} placement="bottomLeft">
                        <div
                          className={[styles.clearfix, styles['user-dropdown']].join(' ')}
                          style={{ height: 64 }}
                        >
                          <div style={{ float: 'left', marginLeft: 12 }}>
                            {currentUser.username}
                          </div>
                          <Avatar icon="user" size={40} style={{ float: 'left', margin: '12px' }} />
                        </div>
                      </Dropdown>
                    </div>
                  </Header>

                  <Content style={{ padding: 16, overflow: 'initial', background: '#f0f2f5' }}>
                    <div style={{ background: '#fff' }}>{children}</div>
                  </Content>
                  <Footer style={{ textAlign: 'center', background: '#f0f2f5' }}>
                    © Web Dev. 2023-2024
                  </Footer>
                </Layout>
              </Layout>
            </Layout>
          )}
        </ConfigProvider>
      </UserContext.Provider>
    );
  }
}

BasicLayout.propTypes = {
  children: PropTypes.element.isRequired,
  location: PropTypes.object.isRequired,
};
